const axios = require('axios')
const sign = require('./sign/xhs/index');

function getNote(noteId) {

  const baseUrl = "https://edith.xiaohongshu.com"
  const api = "/api/sns/web/v1/feed"
  const data = {
    "source_note_id": noteId,
    "image_formats": [
      "jpg",
      "webp",
      "avif"
    ],
    "extra": {
      "need_body_topic": "1"
    }
  }

  const { traceId, xs, xsCommon, xt, cookie } = sign(api, data)

  return axios({
    url: baseUrl + api,
    method: 'post',
    headers: {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'X-B3-Traceid': traceId,
      'X-S': xs,
      'X-S-Common': xsCommon,
      'X-T': xt,
      'Cookie': cookie
    },
    data
  })

}

const controller = async (ctx) => {

  const { noteId } = ctx.request.query

  if (noteId) {
    try {
      const { status, data } = await getNote(noteId)
      if (status === 200 && data.code === 0) {
        ctx.status = 200
        ctx.body = {
          code: 200,
          msg: 'success',
          data: data.data
        }
      } else {
       throw new Error('获取失败')
      }
    } catch (error) {
      ctx.status = 500
      ctx.body = {
        code: 500,
        msg: '服务错误',
        error
      }
    }
    return
  }
  ctx.status = 400
  ctx.body = {
    code: 400,
    msg: 'noteId 不能为空'
  }
}

module.exports = controller
